<template>
  <view>
    <!-- #ifdef MP-WEIXIN -->
    <uv-navbar
      :fixed="false"
      :title="title"
      left-arrow
      @leftClick="$onClickLeft"
    />
    <!-- #endif -->
    <view class="cart-popup">
      <view class="top flex justify-between">
        <text
          >{{ currentLanguageTexts.menuOrdered(getCartGoodsNumber) }}(<text
            style="color: #f56c6c"
            >{{ currentLanguageTexts.pendingOrder }}</text
          >)</text
        >
        <text @tap="handleCartClear">{{ currentLanguageTexts.clear }}</text>
      </view>
      <scroll-view class="cart-list" scroll-y>
        <view class="wrapper">
          <uv-empty
            :text="currentLanguageTexts.noData"
            v-if="cart.length == 0"
          ></uv-empty>
          <view class="item" v-for="(item, index) in cart" :key="index">
            <view class="left">
              <view class="name">{{ getFoodName(item.name) }}</view>
              <view class="props">{{ item.valueStr }}</view>
            </view>
            <view class="center">
              <text>${{ item.price }}</text>
			  <currency :price="item.price"></currency>
            </view>
            <view class="right">
              <button
                type="default"
                plain
                size="mini"
                class="btn"
                hover-class="none"
                @tap="handleCartItemReduce(index)"
              >
                <view class="iconfont iconsami-select"></view>
              </button>
              <view class="number">{{ item.number }}</view>
              <uv-button
                type="primary"
                class="btn"
                size="min"
                hover-class="none"
                @tap="handleCartItemAdd(index)"
                :custom-style="{
                  borderRadius: '40rpx',
                  color: 'rgb(90, 91, 92)',
                }"
              >
                <view class="iconfont iconadd-select"></view>
              </uv-button>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
    <view class="cart-popup" v-for="(cart, index2) in otherCart" :key="index2">
      <view class="top flex justify-between">
        <text
          >{{ cart.uname }},{{
            currentLanguageTexts.menuOrderedYd(getCartNumber(cart.content))
          }}(<text style="color: #f56c6c">{{
            currentLanguageTexts.pendingOrder
          }}</text
          >)</text
        >
      </view>
      <scroll-view class="cart-list" scroll-y>
        <view class="wrapper">
          <uv-empty
            :text="currentLanguageTexts.noData"
            v-if="cart.length == 0"
          ></uv-empty>
          <view class="item" v-for="(item, index) in cart.content" :key="index">
            <view class="left">
              <view class="name">{{ item.name }}</view>
              <view class="props">{{ item.valueStr }}</view>
            </view>
            <view class="center">
              <text>${{ item.price }}</text>
            </view>
            <view class="right">
              <button
                type="default"
                plain
                size="mini"
                class="btn"
                hover-class="none"
              >
                <view class="iconfont iconsami-select"></view>
              </button>
              <view class="number">{{ item.number }}</view>
              <uv-button
                type="primary"
                class="btn"
                size="min"
                hover-class="none"
                :customStyle="{ color: 'rgb(90, 91, 92)' }"
              >
                <view class="iconfont iconadd-select"></view>
              </uv-button>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
    <!--已下单-->
    <view class="cart-popup" v-if="orderData.appDeskOrderVo">
      <view
        class="top flex justify-between mb-2"
        style="background-color: #09b4f1; color: #ffffff"
      >
        <text>{{ currentLanguageTexts.ordered }}</text>
        <text
          >{{ currentLanguageTexts.tableNum }}{{ orderData.deskNumber }}</text
        >
      </view>
      <scroll-view class="cart-list" scroll-y>
        <view class="wrapper2">
          <view
            class="item"
            style="
              background-color: #fdf6ec;
              padding: 10rpx 30rpx;
              margin: 15rpx 0;
              border-radius: 20rpx;
            "
            v-for="(item, index) in orderData.appDeskOrderVo"
            :key="index"
          >
            <view class="flex align-center">
              <view><uv-avatar :src="item.uavatar"></uv-avatar></view>
              <view
                class="flex flex-1 justify-between font-size-sm text-color-assist"
              >
                <view class="flex flex-column ml-2">
                  <text>{{ item.unickname }}</text>
                  <text>{{ formatDateTime(item.addTime) }}</text>
                </view>
              </view>
            </view>
            <uv-divider text=""></uv-divider>
            <view
              class="flex align-center"
              v-for="(good, index2) in item.appDeskOrderGoodsVos"
              :key="index2"
            >
              <view
                ><image
                  :src="good.image"
                  style="width: 100rpx; height: 100rpx"
                ></image
              ></view>
              <view class="flex flex-1 flex-column ml-2 font-size-sm">
                <view class="flex justify-between"
                  ><text class="font-weight-bolder">{{ good.title }}</text
                  ><text style="color: #f56c6c">{{ good.spec }}</text></view
                >
                <view class="flex justify-between mt-1"
                  ><text>${{ good.price }}</text
                  ><text>x{{ good.number }}</text></view
                >
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
    <view class="fixed-bottom flex justify-between align-center bg-white">
      <view class="mx-2 ont-weight-light"
        >应付:<text class="text-danger">${{ getCartGoodsPrice }}</text>
		<currency :price="getCartGoodsPrice1"></currency>
		</view
      >
      <view
        ><uv-button
          type="primary"
          :customStyle="customStyle"
          size="large"
          :text="currentLanguageTexts.placeOrder"
          @click="toPay"
          :custom-style="{
            fontWeight: 'bold',
            color: '#333',
          }"
        ></uv-button
      ></view>
    </view>
    <uv-toast ref="uToast"></uv-toast>
  </view>
</template>

<script setup>
import { ref, toRefs, computed } from 'vue';
import {
  orderDetail,
  getShareCart,
  syncCart,
  getDesk,
  scanBookTable,
} from '@/api/order';
import { useMainStore } from '@/store/store';
import { storeToRefs } from 'pinia';
import { onLoad, onShow, onUnload, onHide } from '@dcloudio/uni-app';
import { formatDateTime } from '@/utils/util';
import { getFoodName } from '@/utils';
import { useWebSocket } from '@/hooks/useWebSocket';
import currency from '@/components/currency/currency.vue';

const main = useMainStore();
const {
  orderType,
  address,
  store,
  location,
  isLogin,
  desk,
  member,
  currentLanguageTexts,
} = storeToRefs(main);
const title = ref(currentLanguageTexts.value.cart);
const cart = ref([]);
const uToast = ref();
const orderData = ref({});
const otherCart = ref([]);
const websocket = ref(null);
const isReconnecting = ref(false);
onShow(() => {
  cart.value = uni.getStorageSync('cart');

  //如果是扫描点餐开启websocket
  if (orderType.value == 'desk') {
    websocketFun();
    // getOtherCart();
    detail();
  }
});

onUnload(() => {
  websocket.value?.close();
});
onHide(() => {
  websocket.value?.close();
});

const getCartGoodsNumber = computed(() => {
  //计算购物车总数
  if (cart.value.length == 0) {
    return 0;
  }
  return cart.value.reduce((acc, cur) => acc + cur.number, 0);
});
const getCartGoodsPrice = computed(() => {
  //计算购物车总价
  if (cart.value.length == 0) {
    return 0;
  }
  let price = cart.value.reduce((acc, cur) => acc + cur.number * cur.price, 0);
  return parseFloat(price).toFixed(2);
});

const getCartGoodsPrice1 = computed(() => {
  //计算购物车总价
  if (cart.value.length == 0) {
    return 0;
  }
  let price = cart.value.reduce((acc, cur) => acc + cur.number * cur.price, 0);
  return parseFloat(price);
});

const customStyle = computed(() => {
  return {
    paddingLeft: '60rpx',
    paddingRight: '60rpx',
  };
});

//获取订单
const detail = async () => {
  let data = await getDesk({ deskId: desk.value.id });
  console.log(data);
  if (data && data.lastOrderNo) {
    orderData.value = await orderDetail(data.lastOrderNo);
  }
};

const getCartNumber = (cart) => {
  if (cart.length == 0) {
    return 0;
  }
  return cart.reduce((acc, cur) => acc + cur.number, 0);
};

const handleCartItemAdd = (index) => {
  cart.value[index].number += 1;
  uni.setStorageSync('cart', JSON.parse(JSON.stringify(cart.value)));
  if (orderType.value == 'desk') {
    noticeCartInfo({
      shopId: store.value.id,
      deskId: desk.value.id,
      content: cart.value,
    });
  }
};
const handleCartItemReduce = (index) => {
  if (cart.value[index].number === 1) {
    cart.value.splice(index, 1);
  } else {
    cart.value[index].number -= 1;
  }
  if (!cart.value.length) {
    cartPopupVisible.value = false;
  }
  uni.setStorageSync('cart', JSON.parse(JSON.stringify(cart.value)));
  if (orderType.value == 'desk') {
    noticeCartInfo({
      shopId: store.value.id,
      deskId: desk.value.id,
      content: cart.value,
    });
  }
};
const noticeCartInfo = async (cart) => {
  await syncCart(cart);
};
const handleCartClear = () => {
  //清空购物车
  uni.showModal({
    title: currentLanguageTexts.value.tip,
    content: currentLanguageTexts.value.sureCancel,
    confirmText: currentLanguageTexts.value.confirm,
    cancelText: currentLanguageTexts.value.cancel,
    success: ({ confirm }) => {
      if (confirm) {
        cart.value = [];
        uni.setStorageSync('cart', JSON.parse(JSON.stringify(cart.value)));
        if (orderType.value == 'desk') {
          noticeCartInfo({
            shopId: store.value.id,
            deskId: desk.value.id,
            content: cart.value,
          });
        }
      }
    },
  });
};
const toPay = () => {
  if (cart.value.length == 0) {
    uToast.value.show({
      message: currentLanguageTexts.value.orderingTip,
      type: 'error',
    });
    return;
  }

  if (!isLogin.value) {
    uni.navigateTo({
      url: '/pages/components/pages/login/login',
    });
    return;
  } else {
    if (store.value.status == 0) {
      uToast.value.show({
        message: currentLanguageTexts.value.notDuringStore,
        type: 'error',
      });
      return;
    }
    // 判断当前是否在配送范围内
    if (
      orderType.value == 'takeout' &&
      store.value.distance < store.value.far
    ) {
      uToast.value.show({
        message: currentLanguageTexts.value.addressNotWithinDiliveryRange,
        type: 'error',
      });
      return;
    }
    uni.showLoading({
      title: currentLanguageTexts.value.loading,
    });
    if (orderType.value == 'desk') {
      const { id, number, people, shopId } = desk.value;
      scanBookTable({
        shopId: shopId,
        deskId: desk.value.id,
        deskPeople: people,
        deskNumber: number,
        user_id: member.value.id,
      });
    }

    uni.setStorageSync('cart', JSON.parse(JSON.stringify(cart.value)));

    uni.navigateTo({
      url: '/pages/components/pages/pay/pay',
    });
  }

  uni.hideLoading();
};
const getOtherCart = async () => {
  let data = await getShareCart({
    shopId: store.value.id,
    deskId: desk.value.id,
  });
  if (data) {
    otherCart.value = data;
  }
};
const websocketFun = () => {
  websocket.value = useWebSocket({
    // 连接成功
    onConnected: async () => {},
    // 收到消息
    onMessage: async (data) => {
      if (data.type == 'sync-menu-msg') {
        let content = JSON.parse(data.content);
        console.log('content：', content);
        console.log('deskId：', content.deskId);
        console.log('cartMsgVoList：', content.cartMsgVoList);
        if (
          store.value.id == content.shopId &&
          desk.value.id == content.deskId
        ) {
          if (content.uid != member.value.id) {
            const index = otherCart.value.findIndex((item) => {
              return (
                item.shopId === content.shopId &&
                item.deskId === content.deskId &&
                item.uid === content.uid
              );
            });
            if (index > -1) {
              otherCart.value[index] = content;
            } else {
              otherCart.value.push(content);
            }
          }
        }
      }
    },
  });
};
</script>

<style lang="scss" scoped>
.cart-popup {
  .top {
    background-color: $bg-color-primary;
    //color: $color-primary;
    color: #5a5b5c;
    padding: 10rpx 30rpx;
    font-size: 24rpx;
    text-align: right;
  }
  .cart-list {
    background-color: #ffffff;
    width: 100%;
    overflow: hidden;
    min-height: 1vh;
    max-height: 60vh;

    .wrapper2 {
      height: 100%;
      //display: flex;
      flex-direction: column;
      padding: 0 10rpx;
      margin-bottom: 156rpx;
    }

    .wrapper {
      height: 100%;
      display: flex;
      flex-direction: column;
      padding: 0 30rpx;
      margin-bottom: 100rpx;

      .item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 30rpx 0;
        position: relative;

        &::after {
          content: ' ';
          position: absolute;
          bottom: 0;
          left: 0;
          width: 100%;
          background-color: $border-color;
          height: 2rpx;
          transform: scaleY(0.6);
        }

        .left {
          flex: 1;
          display: flex;
          flex-direction: column;
          overflow: hidden;
          margin-right: 30rpx;

          .name {
            font-size: $font-size-sm;
            color: $text-color-base;
          }
          .props {
            color: $text-color-assist;
            font-size: 24rpx;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }

        .center {
          margin-right: 120rpx;
          font-size: $font-size-base;
        }

        .right {
          display: flex;
          align-items: center;
          justify-content: space-between;

          .btn {
            width: 46rpx;
            height: 46rpx;
            border-radius: 100%;
            padding: 0;
            text-align: center;
            line-height: 46rpx;
          }

          .number {
            font-size: $font-size-base;
            width: 46rpx;
            height: 46rpx;
            text-align: center;
            line-height: 46rpx;
          }
        }
      }
    }
  }
}
</style>
